package com.ruoyi.design.viewer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;

public class SpringEventTest {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext("com.ruoyi.design.viewer");
        RequestTest request = (RequestTest) context.getBean("requestTest");
        //调用方法，发布事件
        request.doRequest();
    }
}

class RequestEvent extends SpringApplicationEvent {
    public RequestEvent(RequestTest source) {
        super(source);
    }
}

//发布事件
@Component
class RequestTest {
    @Autowired
    private ApplicationContext applicationContext;

    public void doRequest() {
        System.out.println("调用Request类的doRequest方法发送一个请求");
        applicationContext.publishEvent(new RequestEvent(this));
    }
}

//监听事件
@Component
class RequestListener implements SpringApplicationListener<RequestEvent> {
    @Override
    public void onApplicationEvent(RequestEvent event) {
        System.out.println("监听到RequestEvent事件,执行方法");
    }
}